package com.gitee.huanminabc.fast.boot.test;

import com.gitee.huanminabc.jcommon.multithreading.executor.SleepTools;
import com.gitee.huanminabc.jcommon.reflect.ClassUtil;
import com.gitee.huanminabc.fastboot.FastBoot;
import com.gitee.huanminabc.fastboot.context.AppContext;
import com.gitee.huanminabc.fastboot.context.AppContextUtil;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.extension.ExtensionContext;
import org.junit.jupiter.api.extension.ParameterContext;
import org.junit.jupiter.api.extension.ParameterResolver;

import java.lang.reflect.*;
@Slf4j
public class FastBootInjectParameterResolver implements ParameterResolver {

    @Override
    public boolean supportsParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
        Executable executable = parameterContext.getDeclaringExecutable();
        if (executable instanceof Constructor<?>) {
//            log.info("这是构造函数的参数");
            Class<?> testClass = extensionContext.getRequiredTestClass();
            FastBootTest annotation = testClass.getAnnotation(FastBootTest.class);
            if (annotation == null) {
                return false;
            }

            if (!AppContext.projectLoadOk){
                Class<?> value = annotation.value();
                //如果是Object.class就默认为当前测试类的
                if (value == Object.class) {
                    value = testClass;
                }
                FastBoot.run(value);
                //如果服务没有启动完等待
                while (!AppContext.projectLoadOk){
                    SleepTools.ms(100);
                }
            }

            Constructor<?> maxConstructor = ClassUtil.getMaxConstructor(testClass);
            Class<?>[] parameterTypes = maxConstructor.getParameterTypes();
            if (parameterTypes.length == 0) {
                return false;
            }
            //获取参数对应的成员变量必须是final修饰的 并且是private修饰的 并且不是static修饰的
            Parameter declaredField = parameterContext.getParameter();
            //判断是final修饰的, 并且不是static修饰的
            return Modifier.isFinal(declaredField.getModifiers())&& !Modifier.isStatic(declaredField.getModifiers());
        } else if (executable instanceof Method) {
//            log.info("这是方法的参数");
            return AppContextUtil.getBean(parameterContext.getParameter().getType()) != null;
        }
        // ...你的其他判断
        return false;

    }

    @Override
    public Object resolveParameter(ParameterContext parameterContext, ExtensionContext extensionContext) {
        return AppContextUtil.getBean(parameterContext.getParameter().getType());
    }
}